import 'dart:convert';
import 'dart:io';

import 'package:get/get.dart';
import 'package:osg/controllers/http.dart';
import 'package:osg/controllers/my_method.dart';
import 'package:http/http.dart' as http;


import 'package:image_picker/image_picker.dart';



class ImageUploader {
   
  static Future uploadImage() async {
   
     Future<void> muploadImage(File image) async {

        try {
          var request = http.MultipartRequest('POST',
              Uri.parse(Get.find<MyMethod>().myget('upIMG') + '/bbs/upload'));

          request.files.add(
            await http.MultipartFile.fromPath('file', image.path),
          );
          request.headers.addAll({
            'Authorization': Get.find<MyMethod>().myget('token') ?? '',
          });

          var response = await request.send();
          final responseString = await response.stream.bytesToString();
          if (response.statusCode == 200) {
            final jsonData = jsonDecode(responseString);

            return jsonData['data']['url'];
          } else {
            Get.find<HTTPS>().showTost(response.statusCode);
          }
        } catch (e) {
          Get.find<HTTPS>().showTost(e);
        } finally {

        }
      }



      final Rx<File?> selectedImage = Rx<File?>(null);


        try {
          // 选择图片  pickMultipleImages 多选pickImage
          final pickedFile =
               await ImagePicker().pickImage(source: ImageSource.gallery);
             // await ImagePicker().pickMultiImage(limit: 9);

          if (pickedFile == null) return;

          // 更新选中图片
          final imageFile = File(pickedFile.path);
          selectedImage.value = imageFile;

          // 自动触发上传
          Get.find<HTTPS>().loading();
        return  await muploadImage(imageFile);
        } catch (e) {}

    // 处理响应...
  }

  
}
